use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use std::net::UdpSocket;
use std::time::Duration;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    pub agent_id: String,
    pub server_addr: String,
    pub server_urls: Vec<String>,  // 支持多Server地址
    pub addr: String,
    pub labels: HashMap<String, String>,
    pub retry_config: RetryConfig,
    pub health_check: HealthCheckConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetryConfig {
    pub max_retries: u32,
    pub initial_delay_seconds: u64,
    pub max_delay_seconds: u64,
    pub backoff_multiplier: f64,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_retries: 10,
            initial_delay_seconds: 1,
            max_delay_seconds: 300, // 5分钟
            backoff_multiplier: 2.0,
        }
    }
}

impl RetryConfig {
    pub fn initial_delay(&self) -> Duration {
        Duration::from_secs(self.initial_delay_seconds)
    }
    
    pub fn max_delay(&self) -> Duration {
        Duration::from_secs(self.max_delay_seconds)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthCheckConfig {
    pub heartbeat_interval_seconds: u64,
    pub connection_timeout_seconds: u64,
}

impl Default for HealthCheckConfig {
    fn default() -> Self {
        Self {
            heartbeat_interval_seconds: 30,
            connection_timeout_seconds: 10,
        }
    }
}

impl HealthCheckConfig {
    pub fn heartbeat_interval(&self) -> Duration {
        Duration::from_secs(self.heartbeat_interval_seconds)
    }
    
    pub fn connection_timeout(&self) -> Duration {
        Duration::from_secs(self.connection_timeout_seconds)
    }
}

impl AgentConfig {
    pub fn new(server_addr: String, addr: String) -> Self {
        let mut config = Self {
            agent_id: Self::generate_agent_id(),
            server_addr: server_addr.clone(),
            server_urls: vec![server_addr],  // 默认只有一个Server地址
            addr,
            labels: HashMap::new(),
            retry_config: RetryConfig::default(),
            health_check: HealthCheckConfig::default(),
        };
        
        config.load_labels();
        config.load_config_file();  // 加载配置文件中的高级设置
        config
    }
    
    pub fn load_config_file(&mut self) {
        // 从配置文件读取高级配置
        if let Ok(config_content) = std::fs::read_to_string("agent_config.yaml") {
            if let Ok(yaml_config) = serde_yaml::from_str::<serde_yaml::Value>(&config_content) {
                // 加载多Server地址
                if let Some(server_urls) = yaml_config.get("server_urls").and_then(|v| v.as_sequence()) {
                    let mut urls = Vec::new();
                    for url in server_urls {
                        if let Some(url_str) = url.as_str() {
                            urls.push(url_str.to_string());
                        }
                    }
                    if !urls.is_empty() {
                        self.server_urls = urls;
                        self.server_addr = self.server_urls[0].clone(); // 更新主地址
                    }
                }
                
                // 加载重试配置
                if let Some(retry_config) = yaml_config.get("retry_config") {
                    if let Some(max_retries) = retry_config.get("max_retries").and_then(|v| v.as_u64()) {
                        self.retry_config.max_retries = max_retries as u32;
                    }
                    if let Some(initial_delay) = retry_config.get("initial_delay_seconds").and_then(|v| v.as_u64()) {
                        self.retry_config.initial_delay_seconds = initial_delay;
                    }
                    if let Some(max_delay) = retry_config.get("max_delay_seconds").and_then(|v| v.as_u64()) {
                        self.retry_config.max_delay_seconds = max_delay;
                    }
                    if let Some(multiplier) = retry_config.get("backoff_multiplier").and_then(|v| v.as_f64()) {
                        self.retry_config.backoff_multiplier = multiplier;
                    }
                }
                
                // 加载健康检查配置
                if let Some(health_check) = yaml_config.get("health_check") {
                    if let Some(heartbeat) = health_check.get("heartbeat_interval_seconds").and_then(|v| v.as_u64()) {
                        self.health_check.heartbeat_interval_seconds = heartbeat;
                    }
                    if let Some(timeout) = health_check.get("connection_timeout_seconds").and_then(|v| v.as_u64()) {
                        self.health_check.connection_timeout_seconds = timeout;
                    }
                }
            }
        }
    }

    fn generate_agent_id() -> String {
        let uuid_str = uuid::Uuid::new_v4().to_string();
        format!("agent-{}", &uuid_str[..8])
    }

    pub fn load_labels(&mut self) {
        // 从环境变量读取标签
        if let Ok(labels_str) = std::env::var("AGENT_LABELS") {
            for pair in labels_str.split(',') {
                if let Some((k, v)) = pair.split_once('=') {
                    self.labels.insert(k.trim().to_string(), v.trim().to_string());
                }
            }
        }

        // 从配置文件读取标签 (如果存在)
        if let Ok(config_content) = std::fs::read_to_string("agent_config.yaml") {
            if let Ok(yaml_config) = serde_yaml::from_str::<serde_yaml::Value>(&config_content) {
                if let Some(labels) = yaml_config.get("labels").and_then(|v| v.as_mapping()) {
                    for (k, v) in labels {
                        if let (Some(key), Some(value)) = (k.as_str(), v.as_str()) {
                            self.labels.insert(key.to_string(), value.to_string());
                        }
                    }
                }
            }
        }

        // 自动添加系统标签
        self.add_system_labels();
    }

    fn add_system_labels(&mut self) {
        // 添加主机名标签
        if let Ok(hostname) = hostname::get() {
            self.labels.insert("hostname".to_string(), hostname.to_string_lossy().to_string());
        }

        // 添加IP地址标签
        if let Ok(ip) = self.get_local_ip() {
            self.labels.insert("ip".to_string(), ip);
        }

        // 添加操作系统标签
        self.labels.insert("os".to_string(), std::env::consts::OS.to_string());
        self.labels.insert("arch".to_string(), std::env::consts::ARCH.to_string());

        // 如果没有设置role标签，默认设置为agent
        if !self.labels.contains_key("role") {
            self.labels.insert("role".to_string(), "agent".to_string());
        }

        // 如果没有设置env标签，默认设置为development
        if !self.labels.contains_key("env") {
            self.labels.insert("env".to_string(), "development".to_string());
        }
    }

    fn get_local_ip(&self) -> Result<String, std::io::Error> {
        // 尝试从addr中提取IP，如果是0.0.0.0则获取实际IP
        if self.addr.starts_with("0.0.0.0:") {
            // 获取本机实际IP地址
            if let Ok(socket) = UdpSocket::bind("0.0.0.0:0") {
                if let Ok(_) = socket.connect("8.8.8.8:80") {
                    if let Ok(local_addr) = socket.local_addr() {
                        return Ok(local_addr.ip().to_string());
                    }
                }
            }
            // 如果获取失败，返回默认值
            Ok("127.0.0.1".to_string())
        } else {
            // 从addr中提取IP部分
            if let Some(ip_part) = self.addr.split(':').next() {
                Ok(ip_part.to_string())
            } else {
                Ok("127.0.0.1".to_string())
            }
        }
    }

    pub fn get_external_address(&self) -> String {
        // 将0.0.0.0替换为实际的外部IP地址
        if self.addr.starts_with("0.0.0.0:") {
            self.addr.replace("0.0.0.0:", "8.155.160.173:")
        } else {
            self.addr.clone()
        }
    }
}